'use strict';

const Controller = require('egg').Controller;
const jwt=require("jsonwebtoken");
const createRule = {
    stu: {
      type: 'string',
    },
    pwd: {
      type: 'password',
    },
  };

class UserController extends Controller {
  async registry() {//注册
    const { ctx }=this;
    let {name,pwd,stu,role}=ctx.request.body;
    if (!name || !pwd || !stu || !role) {
        ctx.body={
            code:2,
            mes:"缺少参数"
        }
        return;
    }
    let user=await ctx.service.user.user.getuser(stu);
    if (user.length >0) {
        ctx.body={
            code:3,
            mes:"该用户已经注册了"
        }
        return;
    }

    let res =await ctx.service.user.user.registry({...ctx.request.body,pwd:ctx.helper.help(pwd)});
    if (res.affectedRows==1) {
        ctx.body={
            code:0,
            mes:"注册成功"
        }
    }else{
        ctx.body={
            code:1,
            mes:"注册失败"
        }
    }
  }
  async login(){//登录
    const {ctx}=this;
    const { stu, pwd } = ctx.request.body;
    if (!stu || !pwd) {
        ctx.body={
            code:2,
            mes:"缺少参数"
        }
        return;
    }
    //参数校验
    try {
        ctx.validate(createRule);

        let user=await ctx.service.user.user.getuser(stu);
        if (user.length == 0) {
            ctx.body={
                code:2,
                mes:"该用户还没有注册"
            }
            return;
        }
        let res=await this.service.user.user.login(stu,ctx.helper.help(pwd));
        let token=jwt.sign({...res[0]},ctx.app.config.keys,{expiresIn:"10h"});
        if (res.length > 0) {
            ctx.body={
                code:3,
                token,
                uid: res[0].id,
                rid:res[0].role,
                mes:"登录成功"
            }
        }else{
            ctx.body={
                code:4,
                mes:"登录失败"
            }
        }
    } catch (e) {
        ctx.body={
            code:4,
            mes:"参数校验失败"
        }
    }

}
    async getrole(){///头部身份
        const {ctx}=this;
        let {rid}=ctx.query;
        let res=await ctx.service.user.user.getrole(rid)
        if (res.length>0) {
            ctx.body={
                code:0,
                name:res[0].rname
            }
        }else{
            ctx.body={
                code:1,
                mes:"获取身份失败"
            }
        }

        ctx.body=res;
    }
    async getmenu(){
        const {ctx} = this;
        let {rid} =ctx.query;
        let res = await ctx.service.user.user.getmenu(rid)
        ctx.body = res;
    }
    async getstudent(){
        const {ctx} =this ;
        let res = await ctx.service.user.user.getstudent();
        if (res.length>0) {
            ctx.body={
                code:0,
                data:res
            }
        }else{
            ctx.body={
                code:1,
                mes:"查询失败"
            }
        }

    }
}
module.exports = UserController;
